<template>
	<div>
		<article class="wrapper">
			<nav class="nav">
				<nav-container v-on:showMenuOverlay="showMenuExec" v-show="!show_menu_bol">
					<span slot="navbody">
						<section class="body" v-show="!show_detail">
							<div class="storesList">
								<section class="position">
									<span class="locator-green">
										<img src="@/assets/icons/icon-locator-green.svg">
									</span>
									{{localPosition || '未知地点'}}
									<span class="locator-arrow">
										<img src="@/assets/icons/icon-locator-arrow.svg">
									</span>
								</section>
								<section class="search clearfix">
									<div class="storeSearch">
										<input type="text" placeholder="请输入地址查找门店" v-model="store_name">
										<img src="@/assets/icons/icon-search.svg" v-on:click="searchStores()">
									</div>
									<!-- <div class="storeSelect">筛选</div> -->
								</section>
								<section class="nearbyStoresList">
									<section class="nearbyStores clearfix" v-for="(item, index) in nearbyStores" :key="index" @click = "storeClicked(index)" @mouseover = "storeMouseOver(index)" @mouseout = "storeMouseOut(index)" :class="{'storeClicked': clicked === index}">
										<section class="storeLabel">
											<span>{{index + 1}}</span>
											<img src="@//assets/icons/icon-pin-solid-grey.svg">
										</section>
										<section class="storeInfo">
											<div class="storeName">{{item.store_name}}</div>
											<div class="storeAdd">{{item.address}}</div>
											<div class="storeDis">{{item.distance}}km</div>
										</section>
										<section class="moreInfo" @click="showDetail(item.id)">
											<img src="@/assets/icons/icon-info-green.svg">
										</section>
									</section>
									<div class="noStore" v-if="loadingStores">
										<img src="@/assets/loading-svg/loading-bubbles.svg">
									</div>
									<div class="noStore" v-if="!loadingStores && !nearbyStores[0]">找不到门店</div>
								</section>

							</div>
						</section>
					</span>
				</nav-container>
				<nav-overlay v-on:closeMenuOverlay="closeMenuExec" v-show="show_menu_bol">
				</nav-overlay>
				<nav-mobile v-on:showMenuOverlay="showMenuExec"></nav-mobile>
                <nav-detail v-on:showDetail="showDetail" v-show="show_detail" :store_id="store_id"></nav-detail>
			</nav>
			<section id="sAMap" class="content" v-if="true || lgMedia || !show_menu_bol">
			</section>
		</article>
	</div>
</template>

<script>
// import '@/assets/css/styles.css'
import NavContainer from '@/components/navContainer'
import NavOverlay from '@/components/NavOverlay'
import NavMobile from '@/components/navMobile'
import NavDetail from '@/components/navDetail'
import AMap from 'AMap'
import StoresTools from '@/utils/storesTools'
import request from '@/utils/request'
import { debounce } from '@/utils/index'

export default {
	name: 'stores',
	metaInfo: {
		title: '门店查询',
		titleTemplate: '%s | XPEL',
		meta: [
			{
				name: 'keywords',
				content: ''
			},
			{
				name: 'description',
				content: '查询附近的门店位置、营业时间及联系方式。'
			}
		]
	},
	data(){
		return {
			show_menu_bol: false,
			lgMedia: window.matchMedia('(min-width: 1025px)').matches,
			mbMedia: window.matchMedia('(max-width: 640px)').matches,
			map: null,
			localPosition: '',
			storesList: [],
			nearbyStores: [],
			cityInfo: [],
			markers: [],
			storage: null,
			loadingStores: false,
			clicked: 'None',
            store_name: '',
            show_detail: false,
            show_list: true,
            store_id: '',
		}
	},
	mounted(){
		window.matchMedia('(min-width: 1025px)').addListener(()=>{
			this.lgMedia = window.matchMedia('(min-width: 1025px)').matches;
		});
		window.matchMedia('(max-width: 640px)').addListener(()=>{
			this.mbMedia = window.matchMedia('(max-width: 640px)').matches;
		});
		this.initMap();
	},
	components: {
		NavContainer: NavContainer,
		NavOverlay: NavOverlay,
		NavMobile: NavMobile,
        NavDetail: NavDetail
	},
	methods: {
		showMenuExec(){
			this.show_menu_bol = true;
			this.show_list = false;
		},
		closeMenuExec(){
			this.show_menu_bol = false;
            this.show_list = false;
        },
		initMap(){
			// 初始化地图
			this.map = new AMap.Map('sAMap', {
				resizeEnable: true,
				zoom:16
			});
			if(this.mbMedia){
				this.map.setZoom(13);
			}

			// 控件、地理定位、门店列表
			this.addZoomControl();
			this.getLocalPosition();

            // 地图监听
            ["dragend", "mousewheel", "touchmove", "dblclick"].forEach(eventName => {
                this.map.on(eventName, debounce(this.onMapChangedByDragOrZoomChange), 250)
            })
		},
        onMapChangedByDragOrZoomChange() {
            const bounds = this.map.getBounds()
            const center = bounds.getCenter()
            const radius = parseInt(center.distance(bounds.getSouthWest()))
            const params = {
                lat: center.getLat(),
                lng: center.getLng(),
                dist: radius / 1000
            }
            console.log('params: ', params);
            this.showNearbyStores(params)
        },
		addZoomControl(){
			AMapUI.loadUI([
				'control/BasicControl'
			],(BasicControl)=>{
				this.map.addControl(new BasicControl.Zoom({
					position: {right: '16px', bottom: '48px'},
					showZoomNum: false,
				}));
			});
		},
		getLocalPosition(){
			AMap.plugin([
				'AMap.Geolocation',
				'AMap.Geocoder'
			], ()=>{
				let geolocation = new AMap.Geolocation({
						enableHighAccuracy: true,
						timeout: 3000,
						buttonPosition:'RB',
						buttonOffset: new AMap.Pixel(16, 136),
						panToLocation: true,
						zoomToAccuracy: false,
					});
				let geocoder = new AMap.Geocoder();

				this.map.addControl(geolocation);

				geolocation.getCurrentPosition((status, result)=>{
				    console.log(result);
					// 首先获取当前地理位置，如果失败则获取当前城市信息
					if(status == 'complete'){
						let position = result.position,
							lnglat = [position.lng, position.lat];
						geocoder.getAddress(lnglat, (status, result)=>{
							this.localPosition = StoresTools.ReturnAddress(status, result);
						});
						this.showNearbyStores({lat: position.lat, lng: position.lng});
					}else{
						geolocation.getCityInfo((status, result)=>{
							let lnglat = result.center;
							geocoder.getAddress(lnglat, (status, result)=>{
								this.localPosition = StoresTools.ReturnAddress(status, result);
							});

							this.showNearbyStores({lat: position.lat, lng: position.lng});
						});
					}

					if(this.storesList && this.storesList.length !== 0){
						this.loadingStores = false;
					}
				});
			});
		},
		// 获取门店城市信息
		setStorageItems(options){
			let storage = options.storage,
				itemName = options.itemName,
				data = options.data;

			storage.setItem(itemName, JSON.stringify(data));

			if(storage === localStorage){
				let timerName = itemName + '_Timer',
					curTime = new Date().getTime();
				storage.setItem(timerName, JSON.stringify({time:curTime}));
			}
		},
		showNearbyStores(params){
			console.log('showNearbyStores.params: ', params);
            request({
                url: 'api/store/nearBy',
                params
            }).then(res =>{
                if (res.code == 0) {
                    this.nearbyStores = res.data
                    this.map.remove(this.markers);
                    this.markers = [];
                    this.nearbyStores.forEach((item, index) => this.addMarker(item.lng, item.lat, index + 1, '#B0B0B0'))
                }
            })
		},
		addMarker(lng, lat, label, color){
			AMapUI.loadUI(['overlay/SvgMarker'], (SvgMarker)=>{
				StoresTools.AddSvgMarker({
					lng: lng,
					lat: lat,
					label: label,
					Marker: SvgMarker,
					color: color,
					vData: this
				});
			});
		},
		storeClicked(index){
			// 当前门店信息滑动至顶部，SrollArea所对应的元素应为已经设置overflow:auto;的元素
			let nearbyStores = $('.nearbyStores');

			if(this.lgMedia){
				let lSrollArea = $('.nav-container'),
					hdHeight = 97,
					lStep = nearbyStores[index].offsetTop - hdHeight;
				lSrollArea.animate({scrollTop: lStep}, 240);
			}else{
				let mScrollArea = $('.nearbyStoresList'),
					mStep = nearbyStores[index].offsetTop;
				mScrollArea.animate({scrollTop: mStep}, 240);
			}

			// 动态设置门店信息背景颜色
			this.clicked = index;

			// 动态设置地图标记点颜色
			let len = this.markers.length;
			for(let i = 0; i < len; i++){
				let fillColor = StoresTools.GetFillColor({
					item: i,
					vData: this
				});
				if(fillColor === '#00A862'){
					AMapUI.loadUI(['overlay/SvgMarker'], (SvgMarker)=>{
						let shape = new SvgMarker.Shape.WaterDrop({
							height: 28,
							width: 21,
							fillColor: '#B0B0B0'
						});
						this.markers[i].setSvgShape(shape);
					});
				}

			}
			AMapUI.loadUI(['overlay/SvgMarker'], (SvgMarker)=>{
				let shape = new SvgMarker.Shape.WaterDrop({
					height: 28,
					width: 21,
					fillColor: '#00A862'
				});

				let newIndex = this.markersDuplic(index) || index;
				this.markers[newIndex].setSvgShape(shape);

			});
		},
		storeMouseOver(index){
			if(this.clicked === index){
				return ;
			}
			AMapUI.loadUI(['overlay/SvgMarker'], (SvgMarker)=>{
				let shape = new SvgMarker.Shape.WaterDrop({
					height: 28,
					width: 21,
					fillColor: '#00A862'
				});

				let newIndex = this.markersDuplic(index) || index;
				this.markers[newIndex].setSvgShape(shape);
			});
		},
		storeMouseOut(index){
			if(this.clicked === index){
				return ;
			}
			AMapUI.loadUI(['overlay/SvgMarker'], (SvgMarker)=>{
				let shape = new SvgMarker.Shape.WaterDrop({
					height: 28,
					width: 21,
					fillColor: '#B0B0B0'
				});

				let newIndex = this.markersDuplic(index) || index;
				this.markers[newIndex].setSvgShape(shape);
			});
		},
		markersDuplic(index){
			let _self = this,
				len = _self.markers.length,
				halfLen = len/2,
				mLabel = '';

			if(!Number.isInteger(halfLen)){
				return false;
			}

			try{
				mLabel = StoresTools.GetLabel({
					item: halfLen,
					vData: this
				});
			}catch(err){
				console.log(err);
			}

			if(mLabel == '1'){
				let newIndex = halfLen + index;
				return newIndex;
			}
		},
        searchStores() {
            const bounds = this.map.getBounds()
            const center = bounds.getCenter()
            const radius = parseInt(center.distance(bounds.getSouthWest()))
            const store_name = this.store_name
            const params = {
                lat: center.getLat(),
                lng: center.getLng(),
                dist: radius / 1000,
                store_name: store_name,
            }
            console.log('params: ', params);
            this.showNearbyStores(params)
        },
        showDetail(id) {
		    this.store_id = id;
		    this.show_detail = true;
        }
	}
}

</script>

<style scoped>
/*
 *地图控件样式
 */
#sAMap {
	height: 100vh;
	/*
		设置地图图层位于导航菜单下，但会导致地图无法缩放，通过设置导航菜单的z-index属性解决。
		z-index: -1;
	*/
}

.amap-ui-control-zoom {
	width: 35px !important;
}

.my-font-style .amap-simple-marker-label {
	font-size: 12px;
	font-weight: 700;
	padding-top: 2px;
}

/*
 *门店组件样式
 */
.storesList {
	max-width: 100%;
	padding: 0 24px;
	overflow: auto;
	overflow-x: hidden;
}

.position {
	margin-top: 24px;
	font-size: 1.4rem;
	cursor: pointer;
}

.position .locator-green img {
	width:14px;
	height: 18px;
	margin-right: 6px;
}

.position .locator-arrow img {
	width: 10px;
	height: 8px;
	margin-left: 6px;
}

.search {
	width: 100%;
	margin: 6px 0;
	padding: 4px 0;
	font-size: 1.7rem;
	font-weight: 300;
	color: rgba(0, 0, 0, 0.67);
	line-height: 160%;
	letter-spacing: 0.4px;
}

.search .storeSearch {
	display: inline-block;
	float: left;
	width: 80%;
	padding-bottom: 4px;
	border-bottom: 1px solid rgba(0, 0, 0, 0.12);
	transition: all 0.2s ease;
}

.search .storeSearch:hover {
	border-bottom: 1px solid #00A862;
}

.search .storeSearch input {
	float: left;
	width: calc(100% - 24px);
	border: 0;
}

input:focus {
	outline: none;
}

input::-webkit-input-placeholder {
	font-size: 1.6rem;
	color: rgba(0, 0, 0, 0.48);
}

input::-ms-input-placeholder {
	font-size: 1.6rem;
	color: rgba(0, 0, 0, 0.48);
}

input::-moz-placeholder {
	font-size: 1.6rem;
	color: rgba(0, 0, 0, 0.48);
}

input:-moz-placeholder {
	font-size: 1.6rem;
	color: rgba(0, 0, 0, 0.48);
}

.search .storeSearch img {
	float: right;
	width: 24px;
	height: 24px;
	cursor: pointer;
}

.search .storeSelect {
	display: inline-block;
	float: right;
	font-weight: 400;
	opacity: 0.9;
	cursor: pointer;
}

.nearbyStores {
	position: relative;
	padding: 16px 60px;
	margin: 0 -24px;
	font-size: 1.5rem;
	cursor: pointer;
	transition: all 0.2s ease;
}

.nearbyStores:hover {
	background-color: #F2F2F2;
}

.storeLabel {
	position: absolute;
	left: 24px;
	top: calc(50% - 12px);
	width: 24px;
}

.storeLabel span {
	position: absolute;
	top: 4px;
	width: 100%;
	font-size: 1.2rem;
	font-weight: 700;
	color: #fff;
	text-align: center;
}

.storeLabel img {
	width: 100%;
}

.storeInfo {
	letter-spacing: 0.4px;
	line-height: 160%;
}

.storeInfo .storeName {
	font-size: 1.5rem;
	font-weight: 700;
	margin-bottom: 8px;
}

.storeInfo .storeAdd {
	max-width: 312px;
	font-size: 1.4rem;
	color: rgba(0, 0, 0, 0.56);
	font-weight: normal;
	overflow: hidden;
}

.storeInfo .storeDis {
	font-size: 1.4rem;
	font-weight: normal;
}

.moreInfo {
	position: absolute;
	right: 24px;
	top: calc(50% - 11px);
}

.storesList .noStore {
	width: 100%;
	height: 120px;
	font-size: 1.6rem;
	line-height: 120px;
	text-align: center;
}

.storeClicked {
	background-color: #E3E3E3;
}

.storeClicked:hover {
	background-color: #E3E3E3;
}


.storeDetail .close {
    background: url(https://www-static.chinacdn.starbucks.com.cn/prod/assets/icons/icon-close.svg) no-repeat center center;
    box-sizing: inherit;
    color: transparent;
    display: block;
    float: right;
    height: 48px;
    opacity: 0.8;
    overflow: hidden;
    padding: 0;
    margin: -12px;
    -webkit-transition: all 0.1s linear;
    -moz-transition: all 0.1s linear;
    transition: all 0.1s linear;
    width: 48px;
}
.storeDetail h2 {
    font-size: 2.2rem;
}
.storeDetail .adr {
    font-size: 1.6rem;
}
.storeDetail .header_detail {
    height: 60px;
    padding-bottom: 0px;
}

@media (min-width: 1025px)
{

    .nav .body .storesList {
    	padding: 0 16px;
    }

    .nav .body .position {
    	margin-top: 0;
    }

    .nav .body .storeSearch {
    	width: 93%;
    }

    .nav .body .nearbyStoresList {
    	position: absolute;
    	left: 0;
    	width: 100%;
    	padding: 0 16px;
    	overflow: hidden;
    	overflow-y: auto;
    }

    .nav .body .nearbyStoresList .nearbyStores {
    	border-bottom: 1px solid rgba(0, 0, 0, 0.12);
    }

    #sAMap {
		max-height: 330px;
	}

    .storeDetail {
        top: 97px;
        height: calc(100vh - 97px);
        display: table;
        padding: 0;
    }

    .storeDetail .container .header_detail .icon {
        right: 24px;
        top: 24px;
    }
}

@media (max-width: 640px)
{

    .position {
		padding-top: 16px;
		font-size: 1.2rem;
	}

	.nav .body .storeSearch {
    	width: 86%;
    	white-space: nowrap;
    }

    .nav .body .nearbyStoresList {
    	position: absolute;
    	left: 0;
    	top: 434px;
    	width: 100%;
    	height: calc(100vh - 490px);
    }

    #sAMap {
		max-height: 340px;
	}

}

</style>
